package com.yael.utils;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;

public class InitWebParams {
//	private static final Logger logger = Logger.getLogger(InitWebParams.class.getName());
	public static final String DF_GROUP_IDECATOR = "::";
	private static InitWebParams instance = null;
	private Map<String, Object> _params = null;
	private boolean _isInitiated = false;

	private InitWebParams() {
		this._params = new HashMap<String, Object>();
	}
	
	private boolean setParam(String name, String value) {
		if (!"".equals(name)) {
			this._params.put(name, value);
			return true;
		}
		return false;
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, String> getGroup(String groupName){
		return (HashMap<String, String>)_params.get(groupName);
	}

	public String getValue(String paramName) {
		return (String) _params.get(paramName);
	}
	
	public String getValue(String groupName, String paramName) {
		return (String) getGroup(groupName).get(paramName);
	}
	
	public int getIntValue(String paramName) {
		try{
			return Integer.parseInt((String)_params.get(paramName));
		} 
		catch (NumberFormatException e) {
			e.printStackTrace();
			return -1;
		}
	}
	
	public int getIntValue(String groupName, String paramName) {
		try{
			return Integer.parseInt((String) getGroup(groupName).get(paramName));
		} 
		catch (NumberFormatException e) {
			e.printStackTrace();
			return -1;
		}
	}
	
	public void parseParams(ServletConfig config) {		
		parseParams(config, DF_GROUP_IDECATOR);
	}
	
	@SuppressWarnings("unchecked")
	public void parseParams(ServletConfig config, String groupIdecator) {
		
		Enumeration<String> parameters = config.getServletContext().getInitParameterNames();
		while (parameters.hasMoreElements()) {
			String name = (String) parameters.nextElement();
			if(name.contains(groupIdecator)){
				String groupName = name.substring(0,name.indexOf(groupIdecator));
				String subName = Utils.substringAfter(name, groupIdecator);
				if(!"".equals(groupName) && !"".equals(subName)){
					if(_params.get(groupName)==null) _params.put(groupName, new HashMap<String, String>());
					((HashMap<String, String>)_params.get(groupName)).put(subName, config.getServletContext().getInitParameter(name));
				}
			}
			else setParam(name,	config.getServletContext().getInitParameter(name));
		}
		
		_isInitiated = true;
	}
	
	public boolean isInitiated(){
		return _isInitiated;
	}
	
	public static InitWebParams getInstance() {
		if (instance == null) {
			synchronized (InitWebParams.class) {
				InitWebParams initParams = instance;

				if (initParams == null) {
					synchronized (InitWebParams.class) {
						instance = new InitWebParams();
					}
				}
			}
		}

		return instance;
	}	
}
